package com.qiall.omsserver.service.git;

import com.qiall.bashutil.GitScripUtil;
import com.qiall.omsserver.data.entity.AppCodeInfo;
import com.qiall.omsserver.data.mapper.AppCodeInfoMapper;
import com.qiall.omsserver.data.mapper.GitBranchMapper;
import com.qiall.omsserver.event.PullFailEvent;
import com.qiall.omsserver.event.PullSuccessEvent;
import com.qiall.omsserver.service.GitManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class GitManageServiceImpl implements GitManageService {
    @Autowired
    private AppCodeInfoMapper appCodeInfoMapper;

    @Autowired
    private GitBranchMapper gitBranchMapper;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void gitPull(int appId, int branchId) {
        AppCodeInfo codeInfo = appCodeInfoMapper.selectByAppId(appId);
        String branchName = gitBranchMapper.selectByAppId(appId).get(0).getBranchName();
        boolean isSuccess = GitScripUtil.pull(codeInfo.getGitUserName(), codeInfo.getGitUserPassword(), codeInfo.getGitPath(), branchName);
        if (isSuccess) {
            PullSuccessEvent pullSuccessEvent = new PullSuccessEvent(this, appId, branchId);
            applicationContext.publishEvent(pullSuccessEvent);
        } else {
            PullFailEvent pullFailEvent = new PullFailEvent(this, appId, branchId);
            applicationContext.publishEvent(pullFailEvent);
        }
    }
}
